import { useState, useEffect } from 'react'
import { Link, useLocation } from "react-router-dom";
import { IRecruit } from '../../types'
import * as api from '../../services/company.services'

import style from "./style.module.css";
import HomeSearchItem from "../../components/HomeSearchItem"
import HomeRecruitItem from "../../components/HomeRecruitItem"

let obj: any = {}

export default function Search() {
  const location = useLocation<{area: string, keyWord?: string}>()
  const [city, setCity] = useState('')
  const [recruiData, setRecruiData] = useState<IRecruit[]>([])
  const [searchText, setSearchText] = useState<string>('')
  const [filter] = useState(["经验", "学历", "薪资", "规模", "融资"])
  const [workYear] = useState(["不限", "在校生", "应届生", "一年以内", "1-3年", "3-5年", "5-10年", "10年以上",])
  const [education] = useState(["不限", "初中及以下", "中专/中技", "高中", "大专", "本科", "硕士", "博士"])
  const [salary] = useState(["不限", "3K以下", "3-5K", "5-10K", "10-15K", "15-20K", "20-30K", "30-50K"])
  const [companySize] = useState(["不限", "0-20人", "20-99人", "100-499人", "500-999人", "1000-9999人", "10000人以上"])
  const [financeStage] = useState(["不限", "未融资", "天使轮", "A轮", "B轮", "C轮", "D轮及以上", "已上市", "不需要融资"])
  const [filterType] = useState([workYear, education, salary, companySize, financeStage])
  const [isShow, setIsShow] = useState<Boolean[]>([false, false, false, false, false])
  const [state, setState] = useState<Number[]>([0, 0, 0, 0, 0])
  const [size, setSize] = useState<number>(10) 

  // 初始化时请求数据
  useEffect(() => {
    const getData = async () => {
      if (location.state?.keyWord === '') {
        obj = {
          city: location.state?.area
        }
      } else {
        obj = {
          city: location.state?.area,
          keyWords: location.state?.keyWord
        }
      }
      let recruitRows = await api.hotrecruit(obj)
      if (recruitRows.stat === "OK") {
        setRecruiData(recruitRows.result)
      }
    }
    getData()
  }, [location.state?.area, location.state?.keyWord])

  // 筛选条的状态
  const onchange = (num: number) => {
    let isShow2:Boolean[] = []
    isShow.forEach((item, index) => {
      isShow2.push(false)
      if (index === num) {
        isShow2[index] = !item
      }
    })
    setIsShow(isShow2)
  }

  useEffect(() => {
    if (city === '') return
    const getData = async () => {
      obj.city = city
      let recruitRows = await api.hotrecruit(obj)
      if (recruitRows.stat === "OK") {
        setRecruiData(recruitRows.result)
      }
    }
    getData()
  }, [city])

  const getArea = (area: string) => {
    setCity(area)
  }

  // 筛选后再次请求数据
  const getRecruit = async(Citem: string, Pindex: number, Cindex: number) => {
    let isShow1: Boolean[] = []
    const state1: Number[] = state
    state.map((item, index) => {
      isShow1.push(false)
      if (index === Pindex) {
        state1[index] = Cindex
      }
      return item
    })
    setState(state1)
    setIsShow(isShow1)
    const apiType: string[] = ["workYear", "education", "salary", "companySize", "financeStage"]
    apiType.forEach((item, index) => {
      if (index === Pindex && Pindex===2) obj[item] = Citem
      if (index === Pindex && Pindex!==2) obj[item] = Cindex+1
    })
    let recruitRows = await api.hotrecruit(obj)
    if (recruitRows.stat === 'OK') {
      setRecruiData(recruitRows.result)
    }
  }

  const ImpSearch = async(value: string) => {
    if (value === '') return
    obj.keyWords = value
    let recruitRows = await api.hotrecruit(obj)
    if (recruitRows.stat === 'OK') {
      setRecruiData(recruitRows.result)
    }
  }

  const recruitNull = () => {
    if (recruiData.length === 0) {
      return (
        <div className={style.dataNull}>
          <img src="https://static.zhipin.com/zhipin-geek/v452/h5/wap/images/icon-empty.png" alt="" />
          <p>没有找到相关职位</p>
        </div>
      )
    }
  }

  return (
    <div className={isShow.includes(true)? `${style.wrap} ${style.flexed}` : style.wrap} >
      <div className={style.header}>
        <div className={style.search}>
          <div className={style.topSearch}>
            <Link to='/'>
              <span className={style.toHome}></span>
            </Link>
            <div className={style.searchForm}>
              <div className={style.searchWrap}>
                <button className={style.searchBtn} onClick={() => ImpSearch(searchText)}>搜索</button>
                <input type="search" 
                  className={style.searchText} 
                  value={location.state?.keyWord} 
                  autoComplete='off' 
                  placeholder="搜索职位/公司" 
                  onChange={(event) => setSearchText(event.target.value)}
                />
                <HomeSearchItem city={location.state?.area} getArea={getArea} />
              </div>
            </div>
          </div>
        </div>
        {/* 筛选条件 */}
        <div className={style.filter}>
          <ul className={style.filterList}>
            {filter.map((item, index) => {
              return (
                <li 
                  className={`${isShow[index]? style.fliterItem : ''}`} 
                  onClick={() => onchange(index)} 
                  key={index}
                >
                  {item}
                </li>
              )
            })}
          </ul>
        </div>
        <div className={isShow.includes(true)? style.filterContent : `${style.filterContent} ${style.selected}`} >
          <div className={style.mask}>
            {filterType.map((item, index) => {
              return (
                <ul className={isShow[index]? style.contentList : `${style.contentList} ${style.selected}`} key={index}>
                  {item.map((childItem, childIndex) => {
                    return (
                      <li 
                        key={childIndex} 
                        className={state[index]===childIndex? style.active : ''}
                        onClick={() => getRecruit(childItem, index, childIndex)} 
                      >
                        {childItem}
                      </li>
                    )
                  })}
                </ul>
              )
            })}
          </div>
        </div>
      </div>
      <main className={style.recruit}>
        {recruitNull()}
        <div className={style.recruitList}>
          {recruiData?.map((item, index) => {
            if (index < size) {
              return (
                <HomeRecruitItem recruit={item} key={item._id} />
              )
            } else {
              return null
            }      
          })}
          <div className={style.complete} onClick={() => setSize(size + 5)}>
            {size >= recruiData.length ? "没有更多了" : "加载更多"}
          </div>
        </div>
      </main>
    </div>
  )
}